package com.morningstar.flow.service;

import cn.dev33.satoken.stp.StpUtil;
import com.morningstar.common.result.Result;
import com.morningstar.flow.controller.request.CompleteTask;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

import static com.morningstar.flow.flowable.constants.VariableName.NAME_AUDIT;

@Slf4j
@Service
public class FlowTaskService {

    @Resource
    private TaskService taskService;

    @Resource
    private FlowNodeInstanceService flowNodeInstanceService;

    @Resource
    private FlowInstanceTimeLineService flowInstanceTimeLineService;

    /**
     * 完成任务
     *
     * @param completeTask 完成任务参数
     * @return 基本结果类
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> complete(CompleteTask completeTask) {
        Task task = taskService.createTaskQuery().taskId(completeTask.getTaskId()).singleResult();
        if (task == null) {
            return Result.fail("任务不存在");
        }
        Object audit = completeTask.getParams().get(NAME_AUDIT);
        String userId = StpUtil.getLoginId().toString();
        flowNodeInstanceService.completeTask(task, audit);
        flowInstanceTimeLineService.taskComplete(task, Long.parseLong(userId), (Boolean) audit, null);
        taskService.complete(completeTask.getTaskId(), completeTask.getParams());
        // TODO  更新表单数据
        return Result.successNoData();
    }

    /**
     * 完成任务 系统自动
     *
     * @param taskId 任务Id
     * @param audit  审批意见
     */
    @Transactional(rollbackFor = Exception.class)
    public void complete(String taskId, Boolean audit) {
        Map<String, Object> params = new HashMap<>();
        params.put(NAME_AUDIT, audit);
        CompleteTask completeTask = new CompleteTask();
        completeTask.setTaskId(taskId);
        completeTask.setParams(params);
        Task task = taskService.createTaskQuery().taskId(completeTask.getTaskId()).singleResult();
        if (task == null) {
            return;
        }
        flowNodeInstanceService.completeTask(task, audit);
        flowInstanceTimeLineService.taskComplete(task, -99999L, audit, "审批人为空");
        taskService.complete(completeTask.getTaskId(), completeTask.getParams());
    }
}
